﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Web;
using Cherry.Agile.Core.Instrumentation;
 

namespace Cherry.Agile.Core.Lifetime
{
    /// <summary>
    /// Http生命周期实现
    /// </summary>
    public class HttpContextLifetimeManager : LifetimeManager, IDisposable
    {

        private static readonly IClientInstrumentationProvider _instrumentation;
        static HttpContextLifetimeManager()
        {
            if (Container.Current.IsRegistered<IClientInstrumentationProvider>())
            {
                _instrumentation = Container.Current.Resolve<IClientInstrumentationProvider>();
            }
        }
        /// <summary>
        /// 清除缓存项
        /// </summary>
        public static void Clear()
        {
            if (HttpContext.Current == null)
                return;
            var keys = HttpContext.Current.Items.Keys.Cast<object>().ToArray();
            foreach (var key in keys)
            {
                DisposeObject(HttpContext.Current.Items[key] as IDisposable);
                HttpContext.Current.Items.Remove(key);
            }

        }

        private string key;
        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpContextLifetimeManager()
        {
            key = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 获取缓存项
        /// </summary>
        /// <returns></returns>
        public override object GetValue()
        {
            return HttpContext.Current.Items[key];
        }

        /// <summary>
        /// 移除缓存项
        /// </summary>
        public override void RemoveValue()
        {
            HttpContext.Current.Items.Remove(key);
        }

        /// <summary>
        /// 设置缓存项
        /// </summary>
        /// <param name="newValue"></param>
        public override void SetValue(object newValue)
        {
            if (_instrumentation != null)
                _instrumentation.Created();
            HttpContext.Current.Items[key] = newValue;
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            var obj = GetValue() as IDisposable;
            DisposeObject(obj as IDisposable);
            RemoveValue();
        }

        static void DisposeObject(IDisposable obj)
        {
            if (obj != null)
            {
                ServiceFactory.DestroyService(obj,_instrumentation);
                System.Diagnostics.Trace.TraceInformation(string.Format("HttpContextLifetimeManager\tWCF Client {0} disposed.", obj));
            }
        }
    }
}
